package cn.edu.shou.lab.config.utils;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

public class TxtUtil {

    private final static Logger LOGGER = Logger.getLogger(TxtUtil.class.getName());
    private final static String defaultSpiltRowRegex = "(\r\n)+";
    private final static String defaultSpiltColRegex = "(\t)+";

    /**
     * 读取TXT
     * @param txtFile 读取目标TXT
     * @param spiltRowRegex 行分隔符正则表达式
     * @param spiltColRegex 列分隔符正则表达式
     * @param skipRows 跳过行数
     * @param skipCols 跳过列数
     * @param readRows 读取行数
     * @param readCols 读取列数
     * @param charset 字符集
     * @return txt读取到的数据 List<List<String>>
     */
    public static List<List<String>> read(@NotNull File txtFile,
                                          String spiltRowRegex,
                                          String spiltColRegex,
                                          Integer skipRows,
                                          Integer skipCols,
                                          Integer readRows,
                                          Integer readCols,
                                          String charset){
        //初始化，检查条件
        if (!txtFile.exists() || !txtFile.isFile()) {
            throw new RuntimeException("txt file is not exist ！");
        }
        if (spiltRowRegex == null || spiltRowRegex.isEmpty()) {
            spiltRowRegex = defaultSpiltRowRegex;
        }
        if (spiltColRegex == null || spiltColRegex.isEmpty()) {
            spiltColRegex = defaultSpiltColRegex;
        }
        if (skipRows == null) {
            skipRows = 0;
        }
        if (skipCols == null) {
            skipCols = 0;
        }
        if (readRows == null) {
            readRows = Integer.MAX_VALUE;
        }
        if (readCols == null) {
            readCols = Integer.MAX_VALUE;
        }
        if (charset == null || charset.isEmpty()) {
            charset = "UTF8";
        }

        List<List<String>> results;
        //读取TXT得到数据字符串
        String oldDataString = read(txtFile, charset).toString();
        //将TXT数据字符串转为数据List
        List<List<String>> oldDataList = transfer(oldDataString, spiltRowRegex, spiltColRegex);
        //取得数据List中需要的内容
        results = getSpecifiedRowsAndCols(oldDataList,skipRows,skipCols,readRows,readCols);
        return results;
    }


    /**
     * 从指定的TXT文件中，读取数据为 StringBuilder
     * @param txtFile 目标TXT文件
     * @param charset 读取字符集
     * @return StringBuilder
     */
    private static StringBuilder read(File txtFile, String charset){
        InputStreamReader isr = null;
        StringBuilder sb = null;
        try {
            isr = new InputStreamReader(new FileInputStream(txtFile), charset);
            int c;
            sb = new StringBuilder();
            //按字符读取文件
            while ((c = isr.read()) != -1) {
                sb.append((char)c);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.warning(e.getMessage());
        } finally {
            if (isr != null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb;
    }

    /**
     * 将从TXT中读取的字符串，转为 List<List<String>> 格式
     * @param dataString 从TXT中读取的字符串
     * @param spiltColRegex 列分割正则表达式
     * @param spiltRowRegex 行分割正则表达式
     * @return List<List<String>>
     */
    private static List<List<String>> transfer(String dataString,
                                               String spiltRowRegex,
                                               String spiltColRegex){

        List<List<String>> results = new ArrayList<>();
        if(dataString == null || dataString.length() == 0){
            return results;
        }
        String[] rowsString = dataString.split(spiltRowRegex);
        for(String rowString : rowsString){
            List<String> row = Arrays.asList(rowString.split(spiltColRegex));
            results.add(row);
        }
        return results;
    }


    /**
     * 从获取到的txt内容中，取得需要的部分
     * @param dataList 原TXT中的全部内容
     * @param skipRows 跳过行数
     * @param skipCols 跳过列数
     * @param readRows 读取行数
     * @param readCols 读取列数
     * @return List<List<String>>
     */
    private static List<List<String>> getSpecifiedRowsAndCols(List<List<String>> dataList,
                                                              Integer skipRows,
                                                              Integer skipCols,
                                                              Integer readRows,
                                                              Integer readCols){
        List<List<String>> results = new ArrayList<>();
        if(dataList == null || dataList.size() == 0){
            return results;
        }
        for(int i = skipRows ; i < dataList.size() && i < readRows ; i ++){
            List<String> oldRowList = dataList.get(i);
            List<String> newRowList = new ArrayList<>();
            if(oldRowList != null){
                for(int j = skipCols ; j < oldRowList.size() && j < readCols ; j ++){
                    newRowList.add(oldRowList.get(j));
                }
            }
            results.add(newRowList);
        }
        return results;
    }
}
